package com.kantboot.system.user.service.impl;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson2.JSON;
import com.kantboot.system.user.domain.entity.SysToken;
import com.kantboot.system.user.dao.repository.entity.SysTokenRepository;
import com.kantboot.system.user.exception.SystemUserException;
import com.kantboot.system.user.service.ISysTokenService;
import com.kantboot.system.user.setting.SystemUserSetting;
import com.kantboot.util.core.redis.RedisUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class SysTokenServiceImpl implements ISysTokenService {

    @Resource
    private SysTokenRepository repository;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private SystemUserSetting systemUserSetting;

    @Override
    public String generateToken(Long userId) {
        // 获取当前时间戳
        Long currentTimeMillis = System.currentTimeMillis();
        // 获取配置的token过期时间
        Long tokenExpireTime = systemUserSetting.getTokenExpireTime();

        // token
        String token = UUID.randomUUID().toString().replaceAll("-","");
        SysToken sysToken = new SysToken()
                .setToken(token)
                .setUserId(userId)
                .setGmtExpire(new Date(currentTimeMillis + tokenExpireTime));

        // 保存token
        SysToken save = repository.save(sysToken);
        redisUtil.setEx("token:" + token, userId+"", tokenExpireTime, TimeUnit.MILLISECONDS);

        return save.getToken();
    }

    @Override
    public void deleteToken(String token) {
        // 删除redis中的token
        redisUtil.delete("token:" + token);
        // 删除数据库中的token
        repository.deleteByToken(token);
    }

    @Override
    public Long getUserIdByToken(String token) {
        if (token == null) {
            return null;
        }
        // redis的key
        String redisKey = "token:" + token;
        if (redisUtil.hasKey(redisKey)) {
            // 如果redis中有token，直接返回
            return Long.parseLong(redisUtil.get(redisKey));
        }
        SysToken byToken = repository.findByToken(token);
        if (byToken == null) {
            throw SystemUserException.NOT_LOGIN;
        }
        Long userId = byToken.getUserId();
        // 如果数据库中有token，存储到redis中
        if (userId != null) {
            redisUtil.setEx(redisKey, userId+"", systemUserSetting.getTokenExpireTime(), TimeUnit.MILLISECONDS);
        }
        return userId;
    }


    @Override
    public void updateUserIdByToken(String token, Long userId) {
        // 更新数据库中的token
        SysToken byToken = repository.findByToken(token);
        System.err.println(JSON.toJSONString(byToken));
        if (byToken == null) {
            throw SystemUserException.NOT_LOGIN;
        }
        byToken.setUserId(userId);
        repository.save(byToken);
        // 更新redis中的token
        redisUtil.setEx("token:" + token, userId+"", systemUserSetting.getTokenExpireTime(), TimeUnit.MILLISECONDS);
    }
}
